<template>
  <view class="login-container">
    <!-- 登录/注册表单区域 -->
    <view class="form-section">
      <view class="card-container">
        <!-- 登录表单 -->
        <view class="form-container" v-if="isLogin">
          <view class="form-header">
            <text class="form-title">欢迎登录</text>
            <text class="form-subtitle">欢迎回来！<br />我们很想你！</text>
          </view>

          <view class="form-content">
            <view class="input-group">
              <!-- <text class="input-label">邮箱</text> -->
              <input
                class="input-field"
                type="text"
                v-model="loginForm.email"
                placeholder="请输入邮箱"
              />
            </view>

            <view class="input-group">
              <!-- <text class="input-label">密码</text> -->
              <view class="password-input-container">
                <input
                  class="input-field"
                  password
                  :type="showPassword ? 'text' : 'password'"
                  v-model="loginForm.password"
                  placeholder="请输入密码"
                />
                <text class="password-toggle" @click="togglePasswordVisibility">
                  <uni-icons
                    :type="showPassword ? 'eye-slash' : 'eye'"
                    size="20"
                  ></uni-icons>
                </text>
              </view>
            </view>

            <button class="submit-btn" @click="handleLogin">登录</button>

            <view class="form-footer">
              <text class="footer-text">还没有账号？</text>
              <text class="register-link" @click="isLogin = false"
                >立即注册</text
              >
            </view>
          </view>
        </view>

        <!-- 注册表单 -->
        <view class="form-container" v-else>
          <view class="form-header">
            <text class="form-title">创建账号</text>
            <text class="form-subtitle">今天就加入我们的社区！</text>
          </view>

          <view class="form-content">
            <view class="input-group">
              <!-- <text class="input-label">邮箱</text> -->
              <view class="email-input-container">
                <input
                  class="input-field"
                  type="text"
                  v-model="registerForm.email"
                  placeholder="您的邮箱"
                />
                <button
                  class="verification-btn"
                  :disabled="countdown > 0"
                  @click="sendVerificationCode"
                >
                  {{ countdown > 0 ? `${countdown}秒` : "获取验证码" }}
                </button>
              </view>
            </view>

            <view class="input-group">
              <!-- <text class="input-label">验证码</text> -->
              <input
                class="input-field"
                type="text"
                v-model="registerForm.verificationCode"
                placeholder="输入验证码"
              />
            </view>

            <view class="input-group">
              <!-- <text class="input-label">密码</text> -->
              <view class="password-input-container">
                <input
                  class="input-field"
                  password
                  v-model="registerForm.password"
                  placeholder="密码"
                />
                <text class="password-toggle" @click="togglePasswordVisibility">
                  <uni-icons
                    :type="showPassword ? 'eye-slash' : 'eye'"
                    size="20"
                  ></uni-icons>
                </text>
              </view>
            </view>

            <view class="input-group">
              <!-- <text class="input-label">确认密码</text> -->
              <input
                class="input-field"
                password
                v-model="registerForm.confirmPassword"
                placeholder="确认密码"
              />
            </view>

            <button class="submit-btn" @click="handleRegister">注册</button>

            <view class="form-footer">
              <text class="footer-text">已有账号？</text>
              <text class="register-link" @click="isLogin = true"
                >立即登录</text
              >
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
  import { ref, onUnmounted } from "vue";
  import { register, sendCode, login } from "@/api/user";
  import { useUserStore } from "@/store/user";

  const isLogin = ref(true);
  const showPassword = ref(false);
  const countdown = ref(0);
  let timer = null;

  const loginForm = ref({
    email: "",
    password: "",
  });

  const registerForm = ref({
    email: "",
    verificationCode: "",
    password: "",
    confirmPassword: "",
  });

  const togglePasswordVisibility = () => {
    showPassword.value = !showPassword.value;
  };
  //发送验证码
  const sendVerificationCode = async () => {
    // 验证邮箱格式
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(registerForm.value.email)) {
      uni.showToast({
        title: "请输入有效的邮箱地址",
        icon: "none",
      });
      return;
    }
    try {
      await sendCode({ email: registerForm.value.email });
    } catch (error) {
      uni.showToast({
        title: error.message || "发送验证码失败，请重试",
        icon: "none",
      });
    }
    uni.showToast({
      title: "验证码已发送",
      icon: "success",
    });
    // 开始倒计时
    countdown.value = 60;
    timer = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearInterval(timer);
      }
    }, 1000);
  };

  const handleLogin = async () => {
    // 验证表单
    if (!loginForm.value.email || !loginForm.value.password) {
      uni.showToast({
        title: "请填写完整信息",
        icon: "none",
      });
      return;
    }

    // 验证邮箱格式
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(loginForm.value.email)) {
      uni.showToast({
        title: "请输入有效的邮箱地址",
        icon: "none",
      });
      return;
    }

    const userStore = useUserStore();
    const res = await login({
      email: loginForm.value.email,
      password: loginForm.value.password,
    });
    console.log(res);

    if (res.code === 200) {
      // 存储token和用户信息
      userStore.setToken(res.data.token);
      userStore.setUserInfo(res.data.user);

      uni.showToast({
        title: "登录成功",
        icon: "success",
      });
      // 登录成功后跳转到首页
      uni.navigateTo({
        url: "/pages/index/index",
      });
    } else {
      uni.showToast({
        title: res.message || "登录失败",
        icon: "none",
      });
    }
  };

  const handleRegister = async () => {
    // 验证表单
    if (
      !registerForm.value.email ||
      !registerForm.value.verificationCode ||
      !registerForm.value.password ||
      !registerForm.value.confirmPassword
    ) {
      uni.showToast({
        title: "请填写完整信息",
        icon: "none",
      });
      return;
    }

    // 验证密码一致性
    if (registerForm.value.password !== registerForm.value.confirmPassword) {
      uni.showToast({
        title: "两次密码输入不一致",
        icon: "none",
      });
      return;
    }

    try {
      await register({
        email: registerForm.value.email,
        code: registerForm.value.verificationCode,
        password: registerForm.value.password,
      });
    } catch (error) {
      uni.showToast({
        title: error.message || "注册失败，请重试",
        icon: "none",
      });
    }
    uni.showToast({
      title: "注册成功",
      icon: "success",
    });

    // 注册成功后跳转到登录页面
    isLogin.value = true;
    // 清空注册表单
    registerForm.value = {
      email: "",
      verificationCode: "",
      password: "",
      confirmPassword: "",
    };
  };

  onUnmounted(() => {
    // 清除定时器
    if (timer) {
      clearInterval(timer);
    }
  });
</script>

<style lang="scss">
  .login-container {
    display: flex;
    flex-direction: column;
    width: 100%;
    min-height: 100vh;
    position: relative;

    .form-section {
      flex: 1;
      width: 100%;
      position: relative;
      display: flex;
      justify-content: center;
      align-items: center;

      .card-container {
        width: 100%;
        max-width: 650rpx;
        padding: 40rpx 50rpx 60rpx;
        position: relative;
      }

      .form-container {
        width: 100%;
        margin-bottom: 20rpx;

        .form-header {
          margin-bottom: 60rpx;
          margin-top: 60rpx;
          padding-left: 10rpx;

          .form-title {
            font-size: 48rpx;
            font-weight: 700;
            color: #1a1a2e;
            margin-bottom: 20rpx;
            display: block;
          }

          .form-subtitle {
            font-size: 32rpx;
            color: #666;
            white-space: pre-line;
            line-height: 1.5;
            display: block;
          }
        }

        .form-content {
          .input-group {
            margin-bottom: 36rpx;
            position: relative;

            .input-label {
              font-size: 28rpx;
              color: #555;
              margin-bottom: 12rpx;
              font-weight: 500;
              display: block;
              padding-left: 10rpx;
            }

            .input-field {
              width: 100%;
              height: 90rpx;
              border: 1rpx solid #d4d4ff;
              border-radius: 10rpx;
              padding: 0 30rpx;
              font-size: 28rpx;
              background-color: #ffffff;
              transition: all 0.3s ease;
              color: #333;
              box-sizing: border-box;

              &:focus {
                border-color: #7c4dff;
                background-color: #ffffff;
                box-shadow: 0 0 12rpx rgba(124, 77, 255, 0.2);
              }
            }

            .password-input-container {
              position: relative;

              .password-toggle {
                position: absolute;
                right: 30rpx;
                top: 50%;
                transform: translateY(-50%);
                color: #7c4dff;
                font-size: 36rpx;
                width: 60rpx;
                height: 60rpx;
                display: flex;
                align-items: center;
                justify-content: center;
              }
            }

            .email-input-container {
              display: flex;
              align-items: center;

              .verification-btn {
                min-width: 180rpx;
                height: 90rpx;
                background-color: #7c4dff;
                color: #fff;
                border: none;
                border-radius: 10rpx;
                font-size: 26rpx;
                margin-left: 20rpx;
                padding: 0 20rpx;
                box-shadow: 0 6rpx 12rpx rgba(124, 77, 255, 0.2);
                transition: all 0.3s ease;

                &:disabled {
                  background-color: #aaa;
                  box-shadow: none;
                }
              }
            }
          }

          .submit-btn {
            width: 100%;
            height: 90rpx;
            background: linear-gradient(135deg, #7c4dff 0%, #6a3de8 100%);
            color: #fff;
            border: none;
            border-radius: 10rpx;
            font-size: 32rpx;
            font-weight: bold;
            margin-top: 50rpx;
            cursor: pointer;
            box-shadow: 0 8rpx 16rpx rgba(124, 77, 255, 0.3);
            letter-spacing: 2rpx;
            transition: all 0.3s ease;

            &:active {
              transform: translateY(2rpx);
              box-shadow: 0 4rpx 8rpx rgba(124, 77, 255, 0.3);
            }
          }

          .form-footer {
            margin-top: 40rpx;
            text-align: center;
            font-size: 28rpx;

            .footer-text {
              color: #666;
            }

            .register-link {
              color: #7c4dff;
              margin-left: 10rpx;
              font-weight: bold;
              cursor: pointer;
            }
          }
        }
      }
    }
  }
</style>
